<template>
 

  <el-container>
    <el-aside width="350px">
      <el-card class="box-card">
        <div  class="text item" style=" display: flex; justify-content: end;">
          <el-button size="mini" type="text" @click="initGeojson">运行</el-button>
        </div>
        <div  class="text item">
          <el-input
            placeholder="geojson请求路径"
            v-model="geojsonPath"
            clearable>
          </el-input>
        </div>
        <div class="text item" style="margin-top: 10px;">
          <el-input
            type="textarea"
            :rows="5"
            placeholder="geojson对象或者字符串"
            v-model="oldGeosjon">
          </el-input>
        </div>
      </el-card>
      <json-viewer style="margin-top: 10px;"
      :value="jsonData"
      :expand-depth=5
      copyable
      boxed
      @copied="onCopy"
      sort/>
    </el-aside>
    <el-main>
      <div class="mapbox-maps">
        <div id="map">      
        </div> 
      </div>   
    </el-main>
  </el-container>  
</template>
<script>
export default{
    name:'PostgisPolymerzation',
    data(){
      return{
        pbfData_1_10: {
          type:'vector',
          tiles:['http://localhost:8081/geoms/get/a_5_10/{z}/{x}/{y}.pbf'],
          minzoom:1,
          maxzoom:10 
        },
        pbfData_1_103: {
          type:'vector',
          tiles:['http://localhost:8081/geoms/get/a_03/{z}/{x}/{y}.pbf'],
          minzoom:1,
          maxzoom:10 
        },
        oldGeosjon:'',
        geojsonPath: 'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json',
        drawer: false,
        map:{},
        geojson: {        
          type:'geojson',
          data:{
          "type": "FeatureCollection",
          "features":[]
          }
        },
        jsonData: {},
      
      }
    },
    mounted() {
      this.loadMap()
    },
    beforeDestroy(){
      this.map.remove()

    },
    methods:{
        
      loadMap() {
          // 英文标注转换为中文   
          // mapboxgl.setRTLTextPlugin(
          //   "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js"
          // );
          this.map =  new mapboxgl.Map({
              accessToken: 'pk.eyJ1Ijoienh0d24iLCJhIjoiY2wzanV3bHduMTZwejNrcXcyd3B1bzBieiJ9.aW_TDqLomftwPvBu7OWqwQ',
              container: 'map',
              style: 'mapbox://styles/mapbox/outdoors-v10', // stylesheet location
              center: [116.79507,32.65542],  //[116.79507,32.65542], // starting position [lng, lat]
              zoom: 15, // starting zoom
              hash: false,
              //pitch: 45,  //地图的角度，不写默认是0，取值是0-60度，一般在3D中使用
              bearing: 0, //地图的初始方向，值是北的逆时针度数，默认是0，即是正北
              antialias: true, //抗锯齿，通过false关闭提升性能
          })
          // 设置语言
          // var language = new MapboxLanguage({ defaultLanguage: "zh" });
          // this.map.addControl(language);

          //地图导航
          var nav = new mapboxgl.NavigationControl();
          this.map.addControl(nav, 'top-right');

          // 比例尺
          var scale = new mapboxgl.ScaleControl({
              maxWidth: 100,
              unit: "metric"
          });
          this.map.addControl(scale,"bottom-left");

          // 全图
          this.map.addControl(new mapboxgl.FullscreenControl());
          // 定位
          this.map.addControl(
              new mapboxgl.GeolocateControl({
              positionOptions: {
                  enableHighAccuracy: true
              },
              trackUserLocation: true
              })
          );
          let that = this;
          this.map.on('load',function () {
             
          that.map.addSource("polymerization",that.geojson);
			  
			    that.map.addSource("gps-pointss",that.geojson);  			 		  			  		             
			  			
          //点聚合分析			
          that.map.addLayer({
            "id": "polymerization",
            "type": "fill",
            "source": "polymerization",              
            "layout": {
              "visibility": "visible",			
            },
            "paint": {
              "fill-color":[
                "case",
                ["boolean",["==",["get","ct"],0],false],"#FFFFFF",
                ["boolean",["==",["get","ct"],1],false],"#FFFFCC",
                ["boolean",["==",["get","ct"],2],false],"#FFCCCC",
                ["boolean",["==",["get","ct"],3],false],"#FFCCCC",
                ["boolean",["==",["get","ct"],4],false],"#FFCCCC",
                ["boolean",["==",["get","ct"],5],false],"#E43961",
                ["boolean",["==",["get","ct"],6],false],"#E43961",
                ["boolean",["==",["get","ct"],7],false],"#E43961",
                ["boolean",["==",["get","ct"],8],false],"#E43961",
                ["boolean",["==",["get","ct"],9],false],"#E43961",
                ["boolean",["==",["get","ct"],10],false],"#E43961",
                ["boolean",["==",["get","ct"],11],false],"#E43961",
                ["boolean",["==",["get","ct"],12],false],"#E43961",
                ["boolean",["==",["get","ct"],13],false],"#E43961",
                ["boolean",["==",["get","ct"],14],false],"#E43961",
                ["boolean",["==",["get","ct"],15],false],"#E43961",
                ["boolean",["==",["get","ct"],16],false],"#E43961",
                "black"
              ]
              ,
              'fill-opacity': 1,
              },
              "maxzoom": 20,
              "minzoom": 0,
            })  
            that.map.addLayer({
              "id": "polymerization_line",
              "type": "line",
              "source": "polymerization",              
              "layout": {
                "visibility": "visible",			
              },
              "paint": {
                "line-opacity": 1,
                "line-color": "#000000",
                "line-width": 1,				
                },
              "maxzoom": 20,
              "minzoom": 0,
            })
		    that.map.addLayer({
          "id": "polymerization_text",
          "type": "symbol",
          "source": "polymerization",              
          "layout": {
            "visibility": "visible",			
            'text-field': '{ct}',		
            'text-size': 12
          },
          paint: {
            'text-halo-color': '#0000FF',
            //'text-halo-width': 2
          },
          "maxzoom": 20,
          "minzoom": 0,
        })

              //geojson  point 数据渲染
              that.map.addLayer({
                  id: "gps-points",
                  type: "circle",
                  source: "gps-pointss",
                  paint: {
                      "circle-radius": 2,
                      "circle-color": "#fff",
                  }
              });
			  //geojson line 数据渲染
			  that.map.addLayer({
                 "id": "geojson-line",
                 "type": "line",
                 "source": "gps-pointss",              
                 "layout": {
					"visibility": "visible",			
				},
                 "paint": {
					 "line-opacity": 1,
					 "line-color": "#45D23E",
					 "line-width": 1,				
                 },
                 "maxzoom": 20,
                 "minzoom": 0,
              });
			  
			  //geojson polygon 数据渲染
			  that.map.addLayer({
                 "id": "geojson-polygon ",
                 "type": "fill",
                 "source": "gps-pointss",              
                 "layout": {
					"visibility": "visible",			
				},
                 "paint": {
					"fill-color":"#ffff",
					'fill-opacity': 1,
                 }
              });
			  
             

            //that.loadGeojson()
			
			//加载点聚合数据
			that.loadgeojsonFormatData();			
			
              
          })
          
      },
      /**
       * 拷贝geojson
       */
      onCopy(e){
          console.log(e)
          alert(e)
      },	 
	  /*
	  * 点聚合分析
	  */
	  loadgeojsonFormatData(){
	    debugger
        let that = this
        let url = "/analysis/format/geojson"
		  that.$axios({
			url: url,
			method: 'post',
			data:{},
		  })
		  .then(function (res) {          
		   console.log(res)
		   let features = []
		   res.data.data.forEach(e=>{
			let geom = JSON.parse(e.row_to_json.value)    
			features=geom.features			
			//features.push({
			// "type": "Feature",
			//  "geometry":geom,
			//  "properties": {"status": "status"}
			//})
		   })
		   that.map.getSource('polymerization').setData({
			  "type": "FeatureCollection",
			  "features":[]
			})
		  that.map.getSource('polymerization').setData({
		  "type": "FeatureCollection",
		  "features":features
		  })
		  })
		  .catch(function (error) {
			// handle error
			console.log(error);
		  })   
	  
	  },
      loadGeojson(){
        debugger
        let that = this
        let url = "/analysis/square"
         // that.$axios({
         //   url: url,
         //   method: 'post',
         //   data:{},
         // })
        //  .then(function (res) {          
        //   console.log(res)
        //   let features = []
        //   res.data.data.forEach(e=>{
        //    let geom = JSON.parse(e.geom)    
        //    features.push(geom)			
        //    //features.push({
            // "type": "Feature",
            //  "geometry":geom,
            //  "properties": {"status": "status"}
            //})
        //   })
        //   that.map.getSource('gps-points').setData({
        //      "type": "FeatureCollection",
        //      "features":[]
         //   })
        //  that.map.getSource('gps-points').setData({
         // "type": "FeatureCollection",
        //  "features":features
        //  })
        //  })
        //  .catch(function (error) {
            // handle error
        //    console.log(error);
        //  })   
		  
		  that.$axios({
            url: "/analysis/geojson",
            method: 'post',
            data:{},
          })
          .then(function (res) {          
           console.log(res)
           let features = []
           res.data.data.forEach(e=>{
            let geom = JSON.parse(e.geom)    
            //features.push(geom)			
            features.push({
             "type": "Feature",
             "geometry":geom,
             "properties": {"status": "status"}
            })
           })
           that.map.getSource('gps-pointss').setData({
              "type": "FeatureCollection",
              "features":[]
            })
          that.map.getSource('gps-pointss').setData({
			  "type": "FeatureCollection",
			  "features":features
          })
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          })   

      },
      /**
       * 渲染geojson数据
       * 
       */
      initGeojson(){
        let that = this
        let ISNULL =false;
        if(that.geojsonPath!=""){
          ISNULL = true
        }
        console.log(that)
        if(ISNULL){
          that.map.getSource('national-park').setData({
            "type": "FeatureCollection",
            "features":[]
          })
          that.map.getSource('national-park').setData(that.geojsonPath)
          let urls = that.geojsonPath.split("https://geo.datav.aliyun.com")
          that.$axios({
            url: urls[1],
            method: 'get',
            data:{},
          })
          .then(function (res) {          
            that.jsonData = res.data
            that.map.flyTo({
              center:res.data.features[0].properties.center,
              zoom: 4,
              bearing: 0,
              speed: 0.8, // make the flying slow
              curve: 1, // change the speed at which it zooms out
            });
            console.log(res);
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          })   
        }else{
          debugger
          if(that.oldGeosjon == "" || that.oldGeosjon ==  {}){
            that.jsonData = {}
            that.map.getSource('national-park').setData({
              "type": "FeatureCollection",
              "features":[]
            })
          }
          if(typeof(that.oldGeosjon) == "string"){
            that.jsonData = JSON.parse(that.oldGeosjon)
            that.map.getSource('national-park').setData({
              "type": "FeatureCollection",
              "features":[]
            })
            that.map.getSource('national-park').setData(that.jsonData)
            that.map.flyTo({
              center:that.jsonData.features[0].properties.center,
              zoom: 4,
              bearing: 0,
              speed: 0.8, // make the flying slow
              curve: 1, // change the speed at which it zooms out
            });
          }
          if(Object.prototype.toString.call(that.oldGeosjon) === '[object Object]'){
            that.jsonData = that.oldGeosjon
            that.map.getSource('national-park').setData({
              "type": "FeatureCollection",
              "features":[]
            })
            that.map.getSource('national-park').setData(that.jsonData)
             that.map.flyTo({
              center:that.jsonData.features[0].properties.center,
              zoom: 4,
              bearing: 0,
              speed: 0.8, // make the flying slow
              curve: 1, // change the speed at which it zooms out
            });
          }
          
        }       
      }
    }
}

</script>
<style scoped lang="scss">
 @import "../../../public/mapbox/mapbox-gl.css";
 .mapbox-maps {
    width: 100%;
    height: calc(100vh - 50px);
    position: relative;
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        bottom:0;
        right: 0;        
    }
    
}
.mapboxgl-canvas {
    outline: none;
}
  /* 隐藏mapbox商标 */
.mapboxgl-ctrl-logo {
    display: none;
} 
.el-aside {
    overflow: auto;
    box-sizing: border-box;
    flex-shrink: 0;
    width: 200px;
    // border: 1px solid red;
    line-height: 19px;
    padding: 10px;
    text-align: left;
}
.jv-container .jv-code.boxed {
    max-height: 100%;
}
</style>